﻿package away3d.primitives.withRB {
	
	import away3d.primitives.Sphere;
	import jiglib.physics.RigidBody;
	import jiglib.geometry.JSphere;
	import jiglib.physics.PhysicsSystem;
	import away3d.containers.Scene3D;
	import jiglib.math.JNumber3D;
	import jiglib.math.JMatrix3D;
	import away3d.core.render.Renderer;
	
	public class SphereWithRB extends Sphere implements IPrimitiveWithRB {
		
		public var rb: RigidBody; 
		private var toRadians: Number = Math.PI / 180;
		
		public function SphereWithRB(objPrimitive:Object = null, objRB:Object = null, scene: Scene3D = null, mov: Boolean = true) {
			super(objPrimitive);
			this.renderer = Renderer.BASIC
			if (scene != null) {
				scene.addChild(this);
			}
			this.rb = new JSphere(this, mov, this.radius);
			this.rb.MoveTo(new JNumber3D(this.x, this.y, this.z), JMatrix3D.IDENTITY);
			PhysicsSystem.getInstance().AddBody(this.rb);
			this.rb.setProps(objRB);
		}
		
		public function updateRigidBodyDimensionFromModel(): void {
			(this.rb as JSphere).Radius = this.radius;
		}

		public function updateRigidBodyPositionFromModel(): void {
			this.rb.MoveTo(new JNumber3D(this.x, this.y, this.z), this.rb.CurrentState.Orientation);
		}
		
		public function updateRigidBodyRotationFromModel(): void {
			var mOrientationX: JMatrix3D = JMatrix3D.rotationMatrix(1, 0, 0, this.rotationX * this.toRadians);
			var mOrientationY: JMatrix3D = JMatrix3D.rotationMatrix(0, 1, 0, this.rotationY * this.toRadians);
			var mOrientationZ: JMatrix3D = JMatrix3D.rotationMatrix(0, 0, 1, this.rotationZ * this.toRadians);
			this.rb.SetOrientation(JMatrix3D.multiply(JMatrix3D.multiply(mOrientationX, mOrientationY), mOrientationZ));
		}
		
		public function updateRigidBodyDimensionAndPositionFromModel(): void {
			this.updateRigidBodyDimensionFromModel();
			this.updateRigidBodyPositionFromModel();
			this.updateRigidBodyRotationFromModel();
		}
		
	}
	
}